#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
QFile Cachefile("Cache.csv");
QString Dir;

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
     ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())  //查找可用串口
    {
        QSerialPort myserial;                   //定义串口类对象
        myserial.setPort(info);                 //设置串口端口
        if(myserial.open(QIODevice::ReadWrite)) //可读可写方式打开串口
        {
            ui->SerialPort_Box->addItem(myserial.portName()); //添加串口号名字 并显示到comboBox
            myserial.close();
        }
    }
    ui->BaudRate_Box->setCurrentText("115200"); //设置默认波特率为115200
    ui->DataBits_Box->setCurrentText("8");      //设置默认数据位为8位
    ui->ChackDigit_Box->setCurrentText("None"); //设置默认无校验位
    ui->StopBit_Box->setCurrentText("1");       //设置默认停止位为1位
    ui->Operation_Button->setText("打开串口");

    line1 = new QLineSeries ();                 //构建曲线序列
    QCline = new QChart();                      //构建图表
    QCline->addSeries(line1);                   //将曲线添加到图表
    QCline->legend()->hide();                   //隐藏图例
    QPen PenColor(Qt::red);
    PenColor.setWidth(3);
    line1->setPen(PenColor);

    axisX = new QValueAxis();
    axisX->setRange(0, 1000);                    //设置范围
    axisX->setLabelFormat("%u");                //设置刻度的格式
    axisX->setGridLineVisible(true);            //网格线可见
    axisX->setTickCount(11);                    //设置多少个大格
    axisX->setMinorTickCount(1);                //设置每个大格里面小刻度线的数目
    //axisX->setTitleText("X");                 //设置描述

    axisY = new QValueAxis();
    axisY->setRange(0,100);
    axisY->setLabelFormat("%u");
    axisY->setGridLineVisible(true);
    axisY->setTickCount(11);
    axisY->setMinorTickCount(1);
    //axisY->setTitleText("Y");
    QCline->addAxis(axisX, Qt::AlignBottom);    //下：Qt::AlignBottom  上：Qt::AlignTop
    QCline->addAxis(axisY, Qt::AlignLeft);      //左：Qt::AlignLeft    右：Qt::AlignRight
    line1->attachAxis(axisX);                   //把数据与坐标轴绑定
    line1->attachAxis(axisY);                   //把数据与坐标轴绑定



    CVdialog = new CV_Setting(this);
    ITdialog = new IT_Setting(this);
    ITdialog->setModal(false);
    CVdialog->setModal(false);
    connect(CVdialog,SIGNAL(CV_Sendsignal()),this,SLOT(CV_Receiver()));
    connect(ITdialog,SIGNAL(IT_Sendsignal()),this,SLOT(IT_Receiver()));

    //ui->widget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    ui->widget->setChart(QCline);

    timer = new QTimer();                                       //设置定时器，产生虚拟数据
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
//    timer->start(1000);

//    time_run = new QTimer();                                        //运行时间显示定时器
//    connect(time_run,SIGNAL(timerunout()),this,SLOT(runupdate()));
//    time_run->start(1000);

    Cachefile.open(QIODevice::WriteOnly);                           //以只写方式打开缓存文件
    Cachefile.write("");                                            //清空文件内容
    Cachefile.close();                                              //关闭文件
    Dir=QDir::currentPath().append("\\Cache.csv");                  //获取缓存文件位置
    ui->DisplayTXT_Box->insertPlainText(Dir);                       //显示缓存文件位置

    Receive_Head=0;
    Receive_End=0;
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_Operation_Button_clicked()
{
    QString str=ui->Operation_Button->text();
    if("打开串口"==str)
    {
        if(ui->SerialPort_Box->currentText()==NULL) QMessageBox::about(this,tr("提示"),tr("串口不可用！"));
        else {
            ui->BaudRate_Box->setEnabled(false);
            ui->DataBits_Box->setEnabled(false);
            ui->ChackDigit_Box->setEnabled(false);
            ui->StopBit_Box->setEnabled(false);
            ui->Operation_Button->setText("关闭串口");
            ui->SerialPort_Box->setEnabled(false);

            serial = new QSerialPort;
            serial->setPortName(ui->SerialPort_Box->currentText());
            serial->open(QIODevice::ReadWrite);
            switch(ui->BaudRate_Box->currentText().toInt())
            {
                case 9600  : serial->setBaudRate(QSerialPort::Baud9600);break;
                case 19200 : serial->setBaudRate(QSerialPort::Baud19200);break;
                case 115200: serial->setBaudRate(QSerialPort::Baud115200);break;
            }

            serial->setDataBits(QSerialPort::Data8);
            serial->setStopBits(QSerialPort::OneStop);
            serial->setParity(QSerialPort::NoParity);
            serial->setFlowControl(QSerialPort::NoFlowControl);
            connect(serial,SIGNAL(readyRead()),this,SLOT(Read_Data()));
            Cachefile.open(QIODevice::WriteOnly|QIODevice::Append);
        }
    }
    if("关闭串口"==str)
    {
        ui->Operation_Button->setText("打开串口");
        ui->BaudRate_Box->setEnabled(true);
        ui->DataBits_Box->setEnabled(true);
        ui->ChackDigit_Box->setEnabled(true);
        ui->StopBit_Box->setEnabled(true);
        ui->SerialPort_Box->setEnabled(true);

        serial->clear();
        serial->close();
        serial->deleteLater();
        Cachefile.close();
    }

}
int num=0,numlast=0;
void MainWindow::Read_Data()
{
    QByteArray buf;

    buf=serial->readAll();
    if((buf.length()==13)&&(buf.data()[0]=='#')&&(buf.data()[10]=='@'))
    {
        QString str;
        for(int i=0;i<9;i++)
        {
            str[i]=buf.data()[i+1];
        }
        Xvalue=num++;
        Yvalue=str.toDouble();
        line1->append(Xvalue,Yvalue);
        if(num>909)axisX->setRange(0,num*1.1);                          //修改坐标轴
        QString wbuf=QString::number(Xvalue)+","+str+"\r\n";            //接收数据写入字符数组
        Cachefile.write(wbuf.toUtf8());                                 //缓存数据写入文件
        //ui->DisplayTXT_Box->insertPlainText(str+"\r\n");
    }
    //ui->DisplayTXT_Box->insertPlainText(QString::number(buf.length())+buf.data()[0]+buf.data()[10]+"\r\n");
    buf.clear();
}

void MainWindow::update()
{
//    Xvalue=num++;
//    Yvalue=rand()%100;
//    line1->append(Xvalue,Yvalue);
    //qreal xUint = QCline->plotArea().width()/(axisX->max()-axisX->min());
    //if(Xvalue>8000) QCline->scroll(xUint,0);
//    if(num>909)axisX->setRange(0,num*1.1);
    Runtime++;
    ui->Time_Label->setText(QString("%1").arg(Runtime/60,2,10,QLatin1Char('0'))+":"+QString("%1").arg(Runtime%60,2,10,QLatin1Char('0')));
/*
    //QFile Savefile("Cache.csv");
    Cachefile.open(QIODevice::WriteOnly|QIODevice::Append);
    for(;num>numlast;numlast++)
    {
        QString str=QString::number(Xvalue)+","+QString::number(Yvalue)+"\r\n";
        Cachefile.write(str.toUtf8());
    }*/
}

void MainWindow::runupdate()
{
   Runtime++;
   ui->Time_Label->setText(QString("%1").arg(Runtime/60,2,10,QLatin1Char('0'))+":"+QString("%1").arg(Runtime%60,2,10,QLatin1Char('0')));
}

void MainWindow::CV_Receiver()
{
    ui->textBrowser->clear();
    ui->textBrowser->insertPlainText("初始电压(V):"+QString::number(CVdialog->CV_Init,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("高电压(V):"+QString::number(CVdialog->CV_Hight,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("低电压(V):"+QString::number(CVdialog->CV_Low,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("结束电压(V):"+QString::number(CVdialog->CV_Final,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("扫描速率(V/s):"+QString::number(CVdialog->CV_ScanRate,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("Sweep Segments:"+QString::number(CVdialog->CV_SweepSeg,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("取样间隔(S):"+QString::number(CVdialog->CV_Sample,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("退出时间(S):"+QString::number(CVdialog->CV_QuietTime,10,2)+"\r\n");
}

void MainWindow::IT_Receiver()
{
    ui->textBrowser->clear();
    ui->textBrowser->insertPlainText("初始电压(V):"+QString::number(ITdialog->IT_Init,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("取样间隔(S):"+QString::number(ITdialog->IT_Sample,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("运行时间(S):"+QString::number(ITdialog->IT_RunTime,10,2)+"\r\n");
    ui->textBrowser->insertPlainText("退出时间(S):"+QString::number(ITdialog->IT_QuitTime,10,2)+"\r\n");
}

void MainWindow::on_SelectCV_Button_clicked()
{
    CVdialog->show();

}

void MainWindow::on_SelectIT_Button_clicked()
{
    ITdialog->show();
}

void MainWindow::on_StartMeaButton_clicked()
{
    if(((CVdialog->CV_Hight)>0.01)||((ITdialog->IT_RunTime)>0.01))
    {
        QString str=ui->StartMeaButton->text();

        if(str=="开始测量")
        {
            timer->start(1000);                                        //测试用定时器中产生虚拟数据，打开定时器
//            time_run->start(1000);                                      //运行时间显示定时器
            Runtime=0;
            ui->StartMeaButton->setText("结束测量");
            ui->RemoveButton->setEnabled(false);
            ui->Save_Button->setEnabled(false);
            //Cachefile.open(QIODevice::WriteOnly|QIODevice::Append);
            num=0;
        }else
        {
            if(timer->isActive()) timer->stop();                      //测试用产生虚拟数据，关机定时器
//            if(time_run->isActive()) time_run->stop();                  //运行时间显示定时器
            ui->StartMeaButton->setText("开始测量");
            ui->RemoveButton->setEnabled(true);
            ui->Save_Button->setEnabled(true);
        }
    }
    else QMessageBox::about(this,tr("提示"),tr("请先设置参数"));
}

void MainWindow::on_RemoveButton_clicked()
{
    line1->clear();
    num=0;
    ui->Time_Label->setText("00:00");
}

void MainWindow::on_Save_Button_clicked()
{
    if(num==0) QMessageBox::about(this,tr("提示"),tr("无数据，保存失败！"));
    else{
        Cachefile.close();
        QString fileName=QFileDialog::getSaveFileName(this,tr("保存为"),"",tr(".csv"))+".csv";
        ui->DisplayTXT_Box->setText(fileName);
        QFile::copy(Dir,fileName);
    }
}

void MainWindow::on_SendPar_Button_clicked()
{
    if(ui->Model_Box->currentText()=="CV法")
    {
        if(CVdialog->CV_QuietTime==0) QMessageBox::about(this,tr("提示"),tr("请检查参数"));
    }
    if(ui->Model_Box->currentText()=="IT法")
    {
        if(ITdialog->IT_QuitTime==0) QMessageBox::about(this,tr("提示"),tr("请检查参数"));
    }
}


